package da

import (
	"d-serv-go/server/core/bean"
	"d-serv-go/server/core/cache"
	"d-serv-go/server/core/conf"
	"d-serv-go/server/core/consts"
	"d-serv-go/server/core/db"
	"d-serv-go/server/core/serv"
	"github.com/kirinlabs/utils/str"
)

type DataSetServ struct {
	serv.CommServ
}

func (c *DataSetServ) AfterSave(paramBean *db.ParamBean, outBean *bean.OutBean) {
	if outBean.IsOk() { // 清除缓存
		dataSet := outBean.Copy()
		sqlBean := db.NewSqlBean().And("DS_ID", outBean.GetStr("ID")).Orders("FIELD_ORDER")
		fields, _ := db.ServDao.Finds("DA_DATASET_FIELD", db.NewParamBean(sqlBean.Bean))
		jsonSql := db.NewSqlBean().And("DS_ID", outBean.GetStr("ID"))
		datas, _ := db.ServDao.Finds("DA_DATASET_JSON", db.NewParamBean(jsonSql.Bean))
		dataSet.Set("FIELDS", fields)
		if len(datas) > 0 {
			dataSet.Set("VIRTUALJSON", datas[0].GetStr("DATA_JSON")) // 虚拟JSON取第一条放入数据集中
		}
		cache.CacheMgr.Set(outBean.GetStr("ID"), dataSet, consts.CACHE_DATASET_ALL)
		keys := cache.CacheMgr.GetKeys(consts.CACHE_DATASET_DATA + conf.ConfMgr.GetStr("DATASET_CACHE_DAYS", "2d"))
		for _, key := range keys {
			if str.StartsWith(key, outBean.GetStr("ID")+":") {
				cache.CacheMgr.Remove(key, consts.CACHE_DATASET_DATA+conf.ConfMgr.GetStr("DATASET_CACHE_DAYS", "2d"))
			}
		}
	}
}
